﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Gp.Scripts.Core.Unit;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Serialization;

namespace Gp.Scripts.Core
{
    [Serializable]
    public class EntityConfigInfo
    {
        [PreviewField(100)] [ReadOnly] [LabelText("预览")]
        public Texture2D portrait;

        [ReadOnly]
        [SerializeField] public int id;
        
        [ShowInInspector]
        [ReadOnly]
        public string name;

        private const string EmptySelection = "（请选择）";
        
        [ShowInInspector]
        [NonSerialized] 
        [ValueDropdown("CharacterNameList")] [LabelText("角色配置信息")] [OnValueChanged("UpdateView")]
        public string characterInfo = EmptySelection;


        public EntityConfigInfo() { }

        public EntityConfigInfo(int id)
        {
            this.id            = id;
            this.name          = Global.GetConfig<Unit.TableUnit>().Get(this.id).Name;
        }


        #if UNITY_EDITOR
        private IEnumerable<string> CharacterNameList
        {
            get
            {
                return Global.GetConfig<Unit.TableUnit>().DataList
                    .Select(cfg =>
                    {
                        string groupName = Enum.GetName(typeof(UnitType), cfg.UnitType);
                        return $"{groupName} /{cfg.Id:D5} - {cfg.Name}";
                    });
            }
        }


        private void UpdateView()
        {
            if (string.IsNullOrEmpty(characterInfo) || characterInfo.Equals(EmptySelection, StringComparison.InvariantCultureIgnoreCase)) return;
            Regex rex = new Regex("/[0-9]*");

            var selectedId = int.Parse(rex.Match(characterInfo).Value.Trim('/'));
            var config     = Global.GetConfig<Unit.TableUnit>().Get(selectedId);

            this.id   = config.Id;
            this.name = config.Name ?? string.Empty;
            portrait = !string.IsNullOrEmpty(config.IconName)
                ? Helpers.ResHelper.LoadAssetInEditor<Texture2D>(ConstBundle.UNIT_Icon, config.IconName)
                : null;

            // EditorOnValueChange?.Invoke();
        }

        // public Action EditorOnValueChange;

        private void UpdateInfo()
        {
            if (id == 0) return;
            var config     = Global.GetConfig<Unit.TableUnit>().GetOrDefault(id);
            if (config == null)
            {
                var message = $"ID: {id} 失效！";
                Debug.LogError(message);
                UnityEditor.EditorWindow.focusedWindow.ShowNotification(new GUIContent(message));
                return;
            }

            name = config.Name;
            portrait = !string.IsNullOrEmpty(config.IconName)
                ? Helpers.ResHelper.LoadAssetInEditor<Texture2D>(ConstBundle.UNIT_Icon, config.IconName)
                : null;
            
            // EditorOnValueChange?.Invoke();
        }

        [OnInspectorInit]
        public void OnInspectorInit()
        {
            UpdateInfo();
        }
        #endif
    }

    public static class EntityConfigInfoExtensions
    {
        public static bool ValidateInfo(this EntityConfigInfo info)
        {
            var unitConfig = Global.GetConfig<Unit.TableUnit>();
            return unitConfig.ContainsId(info.id) && unitConfig.Get(info.id).UnitType == UnitType.HUMANOID;
        }

        public static ConfigUnit GetUnitConfig(this EntityConfigInfo self)
        {
            return Global.GetConfig<Unit.TableUnit>().Get(self.id);
        }
    }
}